<?php

namespace app\index\Controller;
use app\index\common\Tree;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;

class Base extends Controller {
    protected $request, $param, $post, $get, $module, $controller, $categoryList, $webData, $action, $urlMCA, $urlMC;
    public function __construct() {
        $this->request = Request::instance();
        //请求参数
        $this->param = $this->request->param();
        $this->post = $this->request->post();
        $this->get = $this->request->get();
        $this->module = $this->request->module();
        $this->controller = $this->request->controller();
        $this->action = $this->request->action();
        //后去模型/控制器/方法
        $this->urlMCA = $this->module . "/" . Loader::parseName($this->controller) . "/" . $this->action;
        //后去模型/控制器
        $this->urlMC = $this->module . "/" . Loader::parseName($this->controller) . "/";

        parent::__construct();
    }
    public function _initialize() {
        //获取主导航
        $currBreadId = @$this->param["id"] ? @$this->param["id"] : "";

        $this->webData["mainNav"] = $this->getMainNavData();
        $this->categoryList = Db::table("think_category")->select();

        $this->webData["breadCrumb"] = $this->getBreadcrumb($currBreadId, $this->categoryList);

    }

    public function getMainNavData() {
        $res = Db::table("think_category")->where("id", "<>", 1)->select();
        $tree = new Tree();
        $tree->init($res);
        return $tree->getNav();
    }
    protected function fetch($template = '', $vars = [], $replace = [], $config = []) {
        parent::assign(['webData' => $this->webData]);
        return $this->view->fetch($template, $vars, $replace, $config);
    }

    //  public function getBreadcrumb($currentNavId, $menuList, $navStr = "") {

    public function getBreadcrumb($currentNavId, $categoryList, $str = "") {

        if (!$currentNavId && $currentNavId != 0) {
            return false;
        }
        if (is_array($categoryList)) {
            foreach ($categoryList as $key => $value) {
                if ($value["id"] == $currentNavId) {
                    if (!$str) {
                        $bread = "<span>" . $value["name"] . "</span>";
                    } else {
                        $bread = "<a href='" . url("index/category/article", "id=" . $value["id"]) . "'>" . $value["name"] . "</a> ->";
                    }

                    $str = $bread . $str;
                    $str = $this->getBreadcrumb($value["pid"], $categoryList, $str);
                }
            }
        }

        return $str;
    }
}
?>
